import { useRef, useState } from "react"

export default function Demo07() {
  const [count, setCount] = useState(0)
  const timer = useRef<NodeJS.Timeout|null>(null)
  const handleStart = () => {
    console.log('开始计时');
    
    timer.current = setInterval(() => {
      setCount((count) => count + 1) // 这里必须用函数赋值
      console.log(count) // 这里打印永远是0
    }, 100)
  }
  const handleEnd = () => {
    console.log('结束计时');
    if (timer.current) 
      clearInterval(timer.current)
  }
  
  return (
    <>
      <h1>useRef作用</h1>
      <p>1、操作DOM</p>
      <p>2、存储数据</p>
      <h1>实际应用</h1>
      <div>{count}</div>
      <button onClick={handleStart}>开始计时</button>
      <button onClick={handleEnd}>结束计时</button>
    </>
  )
}
